package spindles.api.db;

import static spindles.api.db.DB.runCmd;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import spindles.api.domain.SleepSession;

import com.sleepycat.je.DatabaseException;
import com.sleepycat.persist.EntityCursor;

public class SleepSessionDAO extends DAO<SleepSession> {

	public SleepSessionDAO() {
		super(SleepSession.class, "personID");		
	}	
	
	public Set<SleepSession> findSleepSessions(final long personID) {
		final Set<SleepSession> result = new HashSet<SleepSession>();

		runCmd(new DBCommand() {
			public void execute() throws DatabaseException {
				final EntityCursor<SleepSession> sleeps = 
					longSecondaryIndex.subIndex(personID).entities();
				runCmd(new Closeable<SleepSession>(sleeps){					
					public void execute(EntityCursor<SleepSession> cursor) throws DatabaseException {						
						for(SleepSession s : cursor){
							result.add(s);
						}
					}					
				});
			}
		});

		return result;
	}
	
	public SleepSession findSleepSession(Date sleepStart, long personID) {		
		Set<SleepSession> sleeps = findSleepSessions(personID);		
		for(SleepSession s : sleeps){
			if(s.getDate().equals(sleepStart)){
				return s;
			}
		}		
		return null;
	}
	
	
	
	

}
